package cn.tedu.v6;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

/**
 * Version 6 在线用户列表
 */
public class Server {
    private static final Integer PORT = 2333;
    private ServerSocket serverSocket;
    private List<PrintWriter> allOut=new ArrayList<>();
    //1.私有集合保存所有用户名--onlineUsers
    private Set<String> onlineUsers=new HashSet<>();
    private Map<String, String> userDatabase;

    public Server() {
        try {
            serverSocket = new ServerSocket(PORT);
            //2.Server对象启动--main方法--创建服务器之初，完成对账号和密码的赋值。
            userDatabase=new HashMap<>();
            userDatabase.put("用户","7777");
            userDatabase.put("密码","882686");
        } catch (BindException e) {
            System.out.println("端口号重复申请，推荐换个端口号");
        } catch (IOException e) {
            System.out.println("申请端口号失败了");
        }
    }

    public static void main(String[] args) {
        new Server().start();
    }
    public void start() {
        try {
            while (true) {
                System.out.println("-----等待客户端链接-----");
                Socket socket = serverSocket.accept();
                String ip = socket.getInetAddress().getHostAddress();
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("和服务器断开了");
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
            }
        }
    }
    private synchronized void broadcastMessage(String message){
        for(PrintWriter pw:allOut){
            pw.println("消息广播"+message);
        }
    }
    //封装方法：同步转发给所有客户端消息 方法名叫onlineUsers “在线用户”+onlineUsers
    //updateOnlineUsers更新在线人数的方法：“在线用户：”+onlineUsers
    //字符串：String userList=“在线用户”+String.join("、",onlineUsers)
    private synchronized void updateOnlineUsers() {
        String userList="在线用户:"+String.join(",",onlineUsers);
        for(PrintWriter pw:allOut){
            pw.println(userList);
        }
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private BufferedReader br;
        private PrintWriter pw;
        private String username;
        private String password;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
                synchronized (allOut) {
                    allOut.add(pw);
                }
            } catch (IOException e) {
                System.out.println("客户端断开通讯");
            }
        }
        private boolean Login(String user,String pass){
            return userDatabase.containsKey(user)&&userDatabase.get(user).equals(pass);
        }
        private void handleChat(){
            new Thread(() -> {
                try {
                    String message;
                    String On;
                    while ((message = br.readLine()) != null) {
                        System.out.println("这是客户端说的：" + message);
                        System.out.println("请服务器端输入：");
                        broadcastMessage(message);

                        if (br.readLine().equalsIgnoreCase("exit")) {  //关写
                            //Close();
                            break;
                        }

                    }
                } catch (IOException e) {
                    System.out.println("服务器端读入失败了");
                }
            }).start();
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("请服务器端输入：");
                String say = input.nextLine();
                pw.println("这是服务器说的：" + say);

                if (say.equalsIgnoreCase("exit")) {  //关读
                    System.out.println(username+"客户端断开连接了，IP是："+ip);
                    pw.println(username+"退出聊天室");
                    Close();
                    break;
                }
            }
        }
        public void run() {
            try {
                pw.println("请输入用户名:");
                username = br.readLine();
                pw.println("请输入密码:");
                password = br.readLine();
                if(Login(username,password)){
                    pw.println("登录成功，欢迎进入聊天室");
                    //3.把所有用户添加至集合中【同步】
                    synchronized (onlineUsers){
                        onlineUsers.add(username);
                    }
                    updateOnlineUsers(); // 更新在线用户列表

                    System.out.println("" + ip + "连接成功了");
                    pw.println("输入exit以关闭聊天");
                    handleChat();
                }else {//不通过的情况
                    pw.println("登录失败，用户名或者密码错了");
                    socket.close();//登录失败，关闭连接
                }
            } catch (NullPointerException e) {
                System.out.println("IO流传入对象，有对象为空，立马核对，建议查看try块中对象可能赋值为null");
            } catch (IOException e) {
                System.out.println("服务器端断开连接");
            } finally {
                Close();
                //4.客户端断开链接，移除当前集合【同步】
                synchronized (allOut) {
                    // 4.客户端断开链接，移除当前集合【同步】
                    onlineUsers.remove(username);
                }
                updateOnlineUsers(); // 更新在线用户列表
                synchronized (allOut) {
                    allOut.remove(pw); // 从输出流列表中移除当前客户端的输出流
                }
            }
        }
        //封装一个针对关闭的功能：Close()
        private void Close(){
            synchronized (allOut) {
                allOut.remove(pw);
            }
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("结束通讯：关闭失败");
                }
            if(pw!=null) pw.close();
            if(socket!=null&&!socket.isClosed())
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("通讯关闭失败");
                }
        }
    }
}